package com.lmx.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lmx.project.common.BaseResponse;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.common.ResultUtils;
import com.lmx.project.exception.BusinessException;
import com.lmx.project.model.dto.team.*;
import com.lmx.project.model.entity.Commpition;
import com.lmx.project.model.entity.Team;
import com.lmx.project.model.entity.Teampreson;
import com.lmx.project.model.entity.Users;
import com.lmx.project.model.vo.TeamVo;
import com.lmx.project.model.vo.UsersVo;
import com.lmx.project.model.vo.team.TeamAndTeamPersonVo;
import com.lmx.project.model.vo.team.TeamAndTeamPersonVoList;
import com.lmx.project.service.CommpitionService;
import com.lmx.project.service.TeamService;
import com.lmx.project.service.TeampresonService;
import com.lmx.project.service.UsersService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author lmx
 * 本类负责有关竞赛队伍的增删改查
 */
@RestController
@RequestMapping("team")
@ResponseBody
public class TeamController {
    @Resource
    private TeamService teamService;
    @Resource
    private TeampresonService teampresonService;


//    @Resource
//    private UsersService  usersService;

    @Resource
    private UsersService usersService;

    @Resource
    private CommpitionService commpitionService;

    /**
     * 创建比赛小组
     */
    @PostMapping
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) throws IOException {
        if (teamAddRequest.getCompitionid() == null || teamAddRequest.getCompitionid() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请选择竞赛");
        }

        if (teamAddRequest.getName() == null || teamAddRequest.getName().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入项目名称");
        }
        //        登录
        UsersVo usersByid = usersService.getUserCurrent(request);
        if (usersByid == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录");
        }
//        Users data = usersByid.getData();

        Team team = new Team();
//        将队长id与队长姓名设置给team
        team.setQueue(usersByid.getId());
        team.setQueuename(usersByid.getName());

//
        BeanUtils.copyProperties(teamAddRequest, team);


        boolean save = teamService.save(team);

        if (save) {
            Teampreson teampreson = new Teampreson();
            teampreson.setTeamname(team.getName());
            teampreson.setTeamid(team.getId());
            teampreson.setUserid(team.getQueue());
            teampreson.setUsername(team.getQueuename());
            teampreson.setDepartment("计算机科学与技术学院");
            teampreson.setIsQueue(1);
            teampreson.setStatu(0);
            teampresonService.save(teampreson);
            return ResultUtils.success(team.getId());
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
        }

    }

    /**
     * 向比赛小组中添加小组内部队员
     */
    @PostMapping("inside")
    public BaseResponse<Boolean> addTeamPersonByInside(@RequestBody TeampresonAddRequest teampresonAddRequest) {
        if (teampresonAddRequest.getUseridList() == null || teampresonAddRequest.getUseridList().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<Users> users = usersService.listByIds(teampresonAddRequest.getUseridList());

        ArrayList<Teampreson> teampresons = new ArrayList<>();

        LambdaQueryWrapper<Teampreson> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teampreson::getTeamid, teampresonAddRequest.getTeamid());
        Team one = teamService.getById(teampresonAddRequest.getTeamid());
        if (one == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍错误");
        }
        String name = one.getName();

        for (Users u : users) {
            Teampreson teampreson = new Teampreson();
            teampreson.setTeamid(teampresonAddRequest.getTeamid());
            teampreson.setUserid(u.getId());
            teampreson.setTeamname(name);
            teampreson.setUsername(u.getName());
            teampreson.setStatu(0);

            teampreson.setDepartment("计算机科学与技术学院");
            teampresons.add(teampreson);
        }
        boolean save = teampresonService.saveBatch(teampresons);
        if (save) {
            return ResultUtils.success(true);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
        }
    }


    /**
     * 向比赛小组中添加小组外部队员
     */
    @PostMapping("oustside")
    public BaseResponse<Boolean> addTeamPersonByOutside(@RequestBody TeampresonAddRequest teampresonAddRequest) {

        if (teampresonAddRequest.getDepartment() == null || teampresonAddRequest.getDepartment().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "院系不能为空");
        }

        if (teampresonAddRequest.getUsername() == null || teampresonAddRequest.getUsername().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "姓名不能为空");
        }
        if (teampresonAddRequest.getTeamid() == null || teampresonAddRequest.getTeamid().equals(0)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不能为空");
        }

        Team byId = teamService.getById(teampresonAddRequest.getTeamid());
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不存在");
        }

        String name = byId.getName();//项目名称


        Teampreson teampreson = new Teampreson();

        BeanUtils.copyProperties(teampresonAddRequest, teampreson);

        teampreson.setStatu(1);
        teampreson.setTeamname(name);
        boolean save = teampresonService.save(teampreson);
        if (save) {
            return ResultUtils.success(true);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
        }

    }


    /**
     * 根据队伍id获取队伍成员
     */
    @PostMapping("getperson")
    public BaseResponse<List<Teampreson>> getPerson(@RequestBody TeampresonQueryRequest teampresonQueryRequest) {

        if (teampresonQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (teampresonQueryRequest.getTeamid() == null || teampresonQueryRequest.getTeamid() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LambdaQueryWrapper<Teampreson> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teampreson::getTeamid, teampresonQueryRequest.getTeamid());
        if (teampresonQueryRequest.getStatu() != null) {
            queryWrapper.eq(Teampreson::getStatu, teampresonQueryRequest.getStatu());
        }


        List<Teampreson> list = teampresonService.list(queryWrapper);
        return ResultUtils.success(list);
    }

//    /**
//     * 获取所有小组
//     */
//    @GetMapping("all")
//    @ApiOperation("获取所有比赛小组")
//    public BaseResponse<List<Team>> getallTeam() {
//        List<Team> list = teamService.list();
//        return ResultUtils.success(list);
//    }

    /**
     * 向比赛小组删除队员
     */
    @GetMapping("delete")
    public BaseResponse<Boolean> deleteTeamPreson(Long id, HttpServletRequest request) throws IOException {
        //        登录
        UsersVo data = usersService.getUserCurrent(request);
//        Users data = usersByid.getData();
        if (data == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        Teampreson byId = teampresonService.getById(id);

        System.out.println(byId.getUserid());
        System.out.println(data.getId());

        Long teamid = byId.getTeamid();
//        根据teamid查询队伍信息获取队长的id
        Team byId1 = teamService.getById(teamid);
        Long queue = byId1.getQueue(); //队长id
        if (!queue.equals(data.getId()) && data.getPermissionlevel() == 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean b = teampresonService.removeById(id);
        if (b) {
            return ResultUtils.success(true);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
        }
    }


    /**
     * 删除比赛小组
     */
    @DeleteMapping
    public BaseResponse<Boolean> deleteTeam(Long id, HttpServletRequest request) throws IOException {
        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //        登录
        UsersVo data = usersService.getUserCurrent(request);
//        Users data = usersByid.getData();
        if (data == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录");
        }

        Team queryteam = teamService.getById(id);
        Long queue = queryteam.getQueue(); // 队长id
        if (!queue.equals(data.getId()) && data.getPermissionlevel() == 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

//        boolean b = teampresonService.removeById(id);

//   删除队员
        LambdaQueryWrapper<Teampreson> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teampreson::getTeamid, id);
        boolean remove = teampresonService.remove(queryWrapper);

//        删除队伍
        boolean save = teamService.removeById(id);
        if (save) {
            return ResultUtils.success(save);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查无此数据");
        }

    }

    /**
     * 修改比赛小组信息
     */
    @PostMapping("update")
    public BaseResponse<Long> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) throws IOException {
        if (teamUpdateRequest.getId() == null || teamUpdateRequest.getId() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请选择竞赛");
        }

        //        登录
        UsersVo data = usersService.getUserCurrent(request);
//        Users data = usersByid.getData();
        if (data == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录");
        }

        Team queryteam = teamService.getById(teamUpdateRequest.getId());
        Long queue = queryteam.getQueue(); // 队长id
//        只有队长有权限修改
        if (!queue.equals(data.getId()) && data.getPermissionlevel() == 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        Team team = new Team();
//
        BeanUtils.copyProperties(teamUpdateRequest, team);

        boolean save = teamService.updateById(team);

        if (save) {
            return ResultUtils.success(team.getId());
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
        }
    }


    /**
     * 根据比赛id查询参加的小组,如果compitionud为空，查询全部
     */
    @GetMapping
    public BaseResponse<List<Team>> getTeam(Long compitionid) {


        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        if (compitionid != null && compitionid != 0) {
            queryWrapper.eq(Team::getCompitionid, compitionid);
        }

        List<Team> list = teamService.list(queryWrapper);

        return ResultUtils.success(list);
    }


    /**
     * 查询我创建的团队
     */
    @GetMapping("myteam")
    public BaseResponse<List<TeamVo>> getTeamUserId(Long userid, HttpServletRequest request) throws IOException {
        if (userid == null || userid == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Team::getQueue, userid);
        List<Team> list = teamService.list(queryWrapper);

        List<TeamVo> collect = list.stream().map(team -> {
            TeamVo teamVo = new TeamVo();
            BeanUtils.copyProperties(team, teamVo);
            if (teamVo.getCompitionid() != null) {
                Commpition byId = commpitionService.getById(teamVo.getCompitionid());
                if (byId != null) {
                    teamVo.setCompitionname(byId.getName());
                }
            }
            return teamVo;
        }).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }


    /**
     * 根据队伍id获取队员
     */
    @GetMapping("teampreson")
    public BaseResponse<List<Teampreson>> getuserByTeamId(Long teamid) {
        LambdaQueryWrapper<Teampreson> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teampreson::getTeamid, teamid);
        List<Teampreson> list = teampresonService.list(queryWrapper);
        return ResultUtils.success(list);
    }

    /**
     * 多条件筛选
     */

//
//    @PostMapping("query")
//    public BaseResponse<TeamAndTeamPersonVoList> getTeamAndTeamPernVo(TeamAndQueryRequest teamAndQueryRequest) {
//
//        TeamAndTeamPersonVoList teamAndTeamPersonVoList = teamService.getTeamAndTeamPersoList(teamAndQueryRequest);
//
//
//        return ResultUtils.success(teamAndTeamPersonVoList);
//
//
//    }


}
